﻿(function () {
    var script = document.createElement("script")
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js?";
    if (script.readyState) {  //IE  
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                method.showImgs();
            }
        };
    } else {  //Others  
        script.onload = function () {
            method.showImgs();
        };
    }    
    document.getElementsByTagName("head")[0].appendChild(script);

})();

var method = {
    minWidth: 100,
    minHeight: 100,
    lastScrollTop: 0,
    overLayerId: "NBget_Overlay",
    imagesContainerId: "NBget_Container",
    thumbImgClass: "ThumbImg",
    thumbImgDivClass: "ThumbImgDiv",
    collectionBtnClass: "CollectionBtn",
    noImgTip: "亲，没有找到合适大小的图片，图片宽高必须大于100像素哦~",
    AppendTagToBody: function (tag) {
        $("body").append(tag);
    },
    //检查图片Src是否为相对地址
    CheckImgSrc: function (img) {
        var src = img.attr("src");
        if (src.indexOf("http") < 0)
            img.attr("src", location.protocol + "//" + location.hostname + src);
        return img;
    },
    //验证图片是否符合要求
    VerifringImage: function (imgSelector) {
        var arr = new Array();
        imgSelector.each(function () {
            var obj = $(this);
            //这里获取构造一个Image对象，用于获取图片的原始宽，高
            var originalImg = new Image();
            originalImg.src = obj.attr("src");
            originalImg.alt = obj.attr("alt");
            var currentImg = $("<img/>").attr({ src: originalImg.src, alt: originalImg.alt, width: originalImg.width, height: originalImg.height });
            if (currentImg.attr("src").indexOf("data:") != 0
                    && obj.width() >= method.minWidth
                    && obj.height() >= method.minHeight) {
                currentImg = method.CheckImgSrc(currentImg);
                if (method.filterSameImg(arr, currentImg))
                    arr.push(currentImg);
            }
        });
        return arr;
    },
    //过滤重复地址的图片
    filterSameImg: function (imgs, currentImg) {
        var flag = true;
        $(imgs).each(function () {
            if ($(this).attr("src") == currentImg.attr("src")) {
                flag = false;
                return false;
            }
        });
        return flag;
    },
    //获取所有符合大小的图片
    getVerifiedImgs: function () {
        var pageImgs = this.VerifringImage($("img:visible"));
        var iframeImgs = this.getIframeImgs();
        return pageImgs.concat(iframeImgs);
    },
    //获取iframe里的images
    getIframeImgs: function () {
        var iframeImgArr = new Array();
        $("iframe").each(function () {
            var iframeDoc = $(this).get(0).contentDocument;
            try {
                var imgs = $(iframeDoc).find("img:visible");
                iframeImgArr = iframeImgArr.concat(method.VerifringImage(imgs));
            } catch (e) {
            }
        });
        return iframeImgArr;
    },
    //悬浮时，显示/隐藏采集按钮
    showCollectionBtn: function (container) {
        container
        .mouseover(function () {
            $(this).find("span").eq(0).css("display", "block");
        })
        .mouseout(function () {
            $(this).find("span").eq(0).css("display", "none");
        });
    },
    //计算缩略图容器的Left值，使其水平居中
    calculateImgContainerLeft: function () {
        return ($("body").get(0).offsetWidth - 1150) / 2 + "px";
    },
    calculateImgMarginTop: function (img) {
        var w = img.width(), h = img.height();
        return Math.max(h, w) > 199 ? h < w ? parseInt(100 - 100 * (h / w)) + "px" : "" : parseInt(100 - h / 2) + "px";
    },
    //生成遮罩层
    generateOverlayer: function () {
        var overyLayer = $("<div/>").attr("id", this.overLayerId);
        this.AppendTagToBody(overyLayer);
    },
    //生成缩略图容器
    generateImageContainer: function () {
        var imageContainer = $("<div/>")
        .css({ left: this.calculateImgContainerLeft() })
        .attr("id", this.imagesContainerId);
        this.AppendTagToBody(imageContainer);
    },
    //生成缩略图外层Ul
    generateImagesWrapUl: function () {
        var ul = $("<ul/>").addClass("NBget_ImgPv");
        $("#" + this.imagesContainerId + "").append(ul);
        return ul;
    },
    //生成logo区域
    generateLogoArea: function () {
        var closeBtn = $("<span/>").addClass("Btn_NBgetClos NBget_ui").text("关闭")
                            .click(function () {
                                method.changeScrollTop(false);
                                $("#" + method.imagesContainerId + "").fadeOut("normal", function () {
                                    $(this).remove();
                                    $("#" + method.overLayerId + "").fadeOut("normal", function () {
                                        $(this).remove();
                                    });
                                });
                            });
        var logo = $("<div/>")
        .attr("id", "NBget_logo")
        .addClass("NBget_ui")
        .append(closeBtn);
        $("#" + method.imagesContainerId + "").append(logo);
    },
    //采集图片
    CollectionImage: function (img) {
        var w = img.width();
        var h = img.height();
        var url = img.attr("src");
        var requrl = "http://www.a.com:4500/CollectionImage.ashx?";
        requrl += "sUrl=" + encodeURIComponent(url);
        requrl += "&w=" + w;
        requrl += "&h=" + h;
        requrl += "&des=asdad";
        requrl += "&format=json&jsoncallback=?";
        alert(requrl);
        $.getJSON(requrl, function (data) {
            alert(data);
        });
    },
    //生成图片缩略图
    generateThumbImg: function (imgOjb) {
        var thumbImg = $("<img/>").attr("src", imgOjb.attr("src"))
        .css({ "margin-top": this.calculateImgMarginTop(imgOjb) });
        var collectionBtn = $("<span/>").css("display", "none").addClass("NBget_ui Btn_NBget")
        .click(function () { method.CollectionImage($(this).prev()); });
        var containerLi = $("<li/>").append(thumbImg).append(collectionBtn);
        this.showCollectionBtn(containerLi);
        return containerLi;
    },
    //调整浏览器上下滚动条
    changeScrollTop: function (flag) {
        var scroll = $(document).scrollTop();
        if (scroll == 0 && this.lastScrollTop == 0)
            return;
        //flag 为True时，将scrollTop重置为0，flag为false时还原scrollTop
        flag ? (this.lastScrollTop = scroll, $(document).scrollTop(0)) :
          ($(document).scrollTop(method.lastScrollTop), this.lastScrollTop = 0);
    },
    //注册CSS样式
    registerCSS: function () {
        if ($("#NB_CollectionCSS") != null) {
            var css = $("<link/>").attr("id", "NB_CollectionCSS").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "http://www.a.com:4500/Content/shantu.css");
            $("head").eq(0).append(css);
        }
    },
    //显示图片采集板块
    showImgs: function () {
        var imgs = this.getVerifiedImgs();
        if (imgs.length <= 0)
        { alert(this.noImgTip); return; }
        //遮罩层
        this.generateOverlayer();
        //缩略图容器
        this.generateImageContainer();
        //Logo区域
        this.generateLogoArea();
        //缩略图外层Ul
        var wrapUl = this.generateImagesWrapUl();
        //改变scrolltop
        this.changeScrollTop(true);

        $(imgs).each(function () {
            wrapUl.append(method.generateThumbImg($(this)));
        });

        this.registerCSS();
    }
};
